import torch.nn as nn
import torch

class MySequential(nn.Module):
    def __init__(self, *args):
        super().__init__()
        for idx, module in enumerate(args):
            # 这里，module是Module子类的一个实例。我们把它保存在'Module'类的成员
            # 变量_modules中。_module的类型是OrderedDict
            self._modules[str(idx)] = module

    def forward(self, X):
        # OrderedDict保证了按照成员添加的顺序遍历它们
        for block in self._modules.values():
            X = block(X)
        return X

class MySequential_list(nn.Module):
    # 使用list
    def __init__(self, *args):
        super(MySequential_list, self).__init__()
        self.sequential = []
        for module in args:
            self.sequential.append(module)

    def forward(self, X):
        for module in self.sequential:
            X = module(X)
        return X


X = torch.rand(1,10)
net = MySequential(nn.Linear(10, 20), nn.ReLU(), nn.Linear(20, 10))
net_list = MySequential_list(nn.Linear(10, 20), nn.ReLU(), nn.Linear(20, 10))
# 结果一样
print(net(X))
print(net_list(X))
# 使用_modules方便打印net的网络结构和参数，而list则无法做到
print(net, '\n', net.state_dict())
print(net_list, '\n', net_list.state_dict())